import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_account_book/pages/record/logic.dart';
import 'package:flutter_account_book/pages/record/widget/add_form.dart';
import 'package:flutter_account_book/utils/db/entities/record_type.dart';
import 'package:flutter_account_book/widgets/custom_icon.dart';
import 'package:flutter_account_book/widgets/placeholder_page.dart';
import 'package:flutter_draggable_gridview/flutter_draggable_gridview.dart';
import 'package:get/get.dart';

class RecordTypePage extends StatelessWidget {
  const RecordTypePage({super.key});

  List<DraggableGridItem> _getItems(
          List<RecordType> record, ThemeData themeData) =>
      List.generate(record.length, (index) {
        final type = record[index];
        return DraggableGridItem(
            isDraggable: true,
            child: Container(
                decoration: BoxDecoration(
                  border: Border.all(
                      width: 0.5,
                      color: themeData.indicatorColor.withAlpha(90)),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    type.type == 0
                        ? CustomIcon.asset(type.iconPath,
                            size: CustomIconSize.middle,
                            backgroundColor: Color(type.backgroundColorHex),
                            color: Color(type.textColorHex))
                        : CustomIcon.text(type.iconPath,
                            size: CustomIconSize.middle,
                            backgroundColor: Color(type.backgroundColorHex),
                            color: Color(type.textColorHex)),
                    Text(type.name)
                  ],
                )));
      });

  @override
  Widget build(BuildContext context) {
    final logic = Get.put(RecordTypeLogic());
    ThemeData themeData = Theme.of(context);
    int isIncome = (Get.arguments["isIncome"] as num).toInt();
    Size screenSize = MediaQuery.of(context).size;
    return Scaffold(
        appBar: AppBar(
          title: Text(isIncome == 0 ? '支出管理' : '收入管理'),
          actions: [
            IconButton(
                onPressed: () async {
                  await Get.to(AddForm(),
                      transition: Transition.downToUp,
                      arguments: {"isIncome": isIncome});
                  logic.reload();
                },
                icon: const Icon(Icons.add))
          ],
        ),
        body: Obx(() => showPlaceholderPage(
            show: logic.state.list.isEmpty,
            type: PlaceholderPageType.notData,
            child: DraggableGridViewBuilder(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
                crossAxisSpacing: 0,
                mainAxisSpacing: 0,
              ),
              dragCompletion: (List<DraggableGridItem> list, int oldIndex,
                  int newIndex) async {
                print('$oldIndex, $newIndex');
                final item = logic.state.list.removeAt(oldIndex);
                if (newIndex > logic.state.list.length) {
                  newIndex = logic.state.list.length;
                }
                logic.state.list.insert(newIndex, item);
                var minIndex = min(oldIndex, newIndex);
                var maxIndex = max(oldIndex, newIndex);
                for (var i = minIndex; i <= maxIndex; i++) {
                  var item = logic.state.list[i];
                  item.order = i;
                  await item.save();
                }
              },
              children: _getItems(logic.state.list, themeData),
              isOnlyLongPress: false,
              dragFeedback: (List<DraggableGridItem> list, int index) {
                return Material(
                  color: Colors.transparent,
                  child: SizedBox(
                    width: screenSize.width / 4,
                    height: screenSize.width / 4,
                    child: list[index].child,
                  ),
                );
              },
              dragPlaceHolder: (List<DraggableGridItem> list, int index) {
                return PlaceHolderWidget(
                  child: Container(
                    color: themeData.highlightColor,
                  ),
                );
              },
            ))));
  }
}
